package com.eduhzy.ttw.teacher.mvp.presenter;

import android.app.Application;
import android.os.Message;

import com.blankj.utilcode.util.ObjectUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.ClassTeacherData;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.teacher.mvp.contract.ClassTransferContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import org.simple.eventbus.EventBus;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-7-17 10:51:03
 */
@ActivityScope
public class ClassTransferPresenter extends BasePresenter<ClassTransferContract.Model, ClassTransferContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    BaseQuickAdapter<ClassTeacherData, AutoBaseViewHolder> mAdapter;

    @Inject
    public ClassTransferPresenter(ClassTransferContract.Model model, ClassTransferContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getTeacherByClass(String id) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("classId", id);
        mModel.getTeacherByClass(map)
                .subscribeOn(Schedulers.io())
                //遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<List<ClassTeacherData>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<ClassTeacherData>> data) {
                        if (data.isResult()) {
                            List<ClassTeacherData> list = null;
                            if (ObjectUtils.isEmpty(data.getData())) {
                                list = new ArrayList<>();
                            } else {
                                list = data.getData();
                            }
                            mAdapter.getData().clear();
                            mAdapter.addData(list);
                        } else {
                            mRootView.showMessage(data.getMessage());
                        }
                        if (ObjectUtils.isEmpty(mAdapter.getData())) {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_data));
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (t instanceof ConnectException || t instanceof UnknownHostException) {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_network));
                        } else {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.load_error));
                        }
                    }
                });
    }

    public void switchClassManager(String id, String oldBzrgh, String bzrgh) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("classId", id);
        map.put("oldBzrgh", oldBzrgh);
        map.put("bzrgh", bzrgh);
        mModel.switchClassManager(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        if (commonData.isResult()) {
                            mRootView.showMessage("转让成功！");
                            Message msg = Message.obtain();
                            msg.what = EventBusTags.TRANSFER_CLASS_SUCCESS;
                            EventBus.getDefault().post(msg, RouterHub.APP_MINECLASSACTIVITY);
                            EventBus.getDefault().post(msg, RouterHub.APP_CLASSDETAILSACTIVITY);
                            mRootView.killMyself();
                        }
                    }
                });


    }
}
